<?php
class CmsAuth extends Zend_Auth  {
	
	
	/**
	 * Static varible containing class itself
	 *
	 * @var self
	 */
	protected static $_instance = null;
	
 	/**
 	 * Returning the instance of CmsAuth object. Classic singltone patern
 	 *
 	 * @return self
 	 */
 	public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
	
    public static function check() {
    	if (self::getInstance()->getIdentity()=="0") {
    		throw new Zend_Controller_Action_Exception("Restricted",404);
    	}
    }
    
    
	public function getIdentity() {
		return parent::getIdentity()=="1" ? "1" : "0";
	}
	
	public function authenticate($username,$password) {
		return parent::authenticate(new CheckAuth($username,$password));
	}
	
}

class CheckAuth implements Zend_Auth_Adapter_Interface {

	private $_isValid = false;
	public static $admin_id;
	
	public function __construct($username,$password) {
		$searchAdmin = MF_Main::getInstance()->Administrator->search();
		$searchAdmin->login_exact = $username;
		$searchAdmin->Make();
		if ($searchAdmin->length()==1) {
			$admin = $searchAdmin->item(0);
			if ($admin->checkPass($password)) {
				$this->_isValid = true;
				
				$adminSession = new Zend_Session_Namespace('Cms_Admin');
				$adminSession->id = $admin->administrator_id;
				$adminSession->login = $admin->login;
			}
		}
	}
	
	/**
	 * @see Zend_Auth_Adapter_Interface::authenticate()
	 *
	 * @return Zend_Auth_Result
	 */
	public function authenticate () { 
		if (!$this->_isValid) {
			$code = Zend_Auth_Result::FAILURE;
			$identify = "0";
			$msgs = array("Ошибка авторизации");
		} else {
			$code = Zend_Auth_Result::SUCCESS;
			$identify = "1";
			$msgs = array("Авторизация прошла успешно");
		}
		return new Zend_Auth_Result($code,$identify,$msgs);
	}

	
}
?>